import router from "@src/router";
import $math from "@src/common/math";
import dayjs from "dayjs";
import { discountMd5 } from "@src/common/discountUtils";
import { getQrInfo, getUserPhone, getWxaMsgTpl } from "@src/api/base";
import { createOrder } from "@src/api/catering";
import payBehavior from "./payBehavior";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import cart from "../../store/cart";
import { queryDiscount } from "@src/api/order";
import wxUtils from "@src/common/wxUtils";
import member from "@src/store/member";
import $cache from "@src/common/wxCache";
import { getDistance } from "@src/common/utils";
import { checkPwdInit, getBaseInfo } from "@src/api/member";
import { getShopStatus, nearByAddress } from "@src/api/catering";

const Private_Domain_Meal_Method = "Private_Domain_Meal_Method";

Component({
  behaviors: [payBehavior, storeBindingsBehavior],
  storeBindings: [
    {
      store: cart,
      fields: ["hasDinnerType", "shopId"],
      actions: ["clearCart"],
    },
    {
      store: member,
      fields: {
        memberPhone: "phone",
      },
    },
  ],
  data: {
    shopInfo: null,
    shopId: null,
    tableNo: null,
    cartList: null,
    num: 0,
    orderType: null,
    totalFee: 0,
    isAppointTime: false,
    discountFee: 0,
    orderRemark: "",
    phone: "",
    discountInfo: null,
    tmplIdsData: null,
    isClick: false,
    remark: "",
    remarkLen: 0,
    dinnerNum: "",
    prnsentList: [],
    dinnerType: "",
    thildVal: "",
    isIos: false,
    isPwdInit: false,
    dinnerObj: "",
    isOpenTime: true,
    temporaryDinnerNum: 1,
    tempInputDinnerNum: "",
    isShowTextareaPlaceholder: true,
    showChangeDinner: false,
    dincountList: [],
    orderTypeName: {
      1: "堂食",
      2: "打包",
      3: "外卖配送",
    },
    showDinnerNum: true,
    deliveryMsg: "",
    errMsg: "",
    deliveryOptions: {
      bookingSpan: {
        type: "DAYS",
        value: 6,
      },
      delayDelivery: null,
      deliveryType: "LOCAL",
      limit: 2,
      minPrice: 100,
      prepareBeginTime: null,
      prepareTime: 0, //备货时间
      remark: "郑雅君快递配送下单提示",
      selectSpan: {
        type: "MINUTES",
        value: 15,
      }, // 选择间隔时间
      serviceTimes: [
        {
          beginTime: 480,
          endTime: 1439,
          weekDays: "",
        },
      ], //营业时间
      status: 1,
    },
  },
  observers: {
    totalFee() {
      console.log("totalFee", this.data.totalFee);
    },
    remark: function (remark) {
      if (!remark) {
        this.setData({
          remarkLen: 0,
        });
      } else {
        this.setData({
          remarkLen: remark.length,
        });
      }
    },
    shopId: function (shopId) {
      if (shopId) {
        this.setShopStatus();
      }
    },
    shopInfo: function (value) {
      if (value != null) {
        this.setTimeDialogOptions();
        this.showDinnerModal();
      }
    },
  },
  methods: {
    onShow() {
      let { dinnerObj, shopInfo } = this.data;
      if (dinnerObj.value === 3) {
        nearByAddress(shopInfo).then((res) => {
          if (res.code == 0) {
            if (!res.data) {
              this.setErrMsg();
              this.setData({ deliveryMsg: "" });
              this.setErrMsg();
            }
          }
        });
      }
      // this.showDinnerModal();
    },
    onLoad() {
      wx.getSystemInfo({
        success: (result) => {
          if (result.system.indexOf("ios") != -1) {
            this.setData({
              isIos: true,
            });
          }
        },
      });
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on("order", (data) => {
        let { shopInfo, shopId, tableNo, cartList, num, totalFee, dinnerObj } =
          data;
        if (totalFee < 0) {
          totalFee = 0;
        }
        let prnsentList = [];
        let thirdlyArr = [];
        // 列表名称
        for (let i = 0; i < cartList.length; i++) {
          let itemCount = cartList[i].count;
          let ruleList = cartList[i].ruleList;
          let proList = {
            id: cartList[i].id,
            count: cartList[i].count,
            ruleList: [],
          };
          if (cartList[i].ruleList && cartList[i].ruleList.length > 0) {
            for (let index = 0; index < ruleList.length; index++) {
              let childList = JSON.parse(ruleList[index].rules);
              for (let idx = 0; idx < childList.length; idx++) {
                if (itemCount >= childList[idx].itemNum) {
                  let obj = {
                    title: ruleList[index].sellgiftName,
                    count: parseInt(childList[idx].giftNum),
                    sellgiftId: ruleList[index].sellgiftId,
                    itemNum: parseInt(childList[idx].itemNum),
                  };
                  proList.ruleList.push(obj);
                }
              }
            }
          }
          thirdlyArr.push(proList);
        }
        this.computedData(thirdlyArr);
        this.setData({
          shopInfo,
          shopId,
          tableNo,
          cartList,
          num,
          totalFee,
          thildVal: totalFee,
          dinnerObj,
        });
        if (totalFee > 0.1) {
          this.autoUseDiscount();
        }
        if (dinnerObj.value == 3) {
          nearByAddress(shopInfo).then((res) => {
            if (res.code == 0) {
              if (res.data) {
                this.setAddress(res.data);
              } else {
                this.setErrMsg();
              }
            }
          });
        }
      });
      this.fetchData();
      this.setTimeDialogOptions();
    },
    onReady() {
      // this.setData({dinnerType:getApp().globalData.dinnerType})
    },

    onLogin() {
      if (this.data.memberPhone) {
        this.setData({
          phone: this.data.memberPhone,
        });
      }
    },
    computedData(list) {
      let thirdlyArr = list;
      let prnsentList = [];
      thirdlyArr.forEach((el, index) => {
        if (el.ruleList.length > 0) {
          let oldData = el.ruleList;
          let proNum = el.count;
          const s = new Set(); //实例化对象
          oldData.forEach((item) => s.add(item.sellgiftId)); //添加值（Set可以去掉重复数据）
          let newData = Array.from(
            {
              length: s.size,
            },
            () => []
          ); //创建指定长度数组并添值
          oldData.forEach((item) => {
            let index = [...s].indexOf(item.sellgiftId); //找到指定下标
            newData[index].push(item); //添加数据
          });
          newData.forEach((ele, index) => {
            var valThird = "";
            ele.forEach((cel, cindex) => {
              if (cel.itemNum <= proNum) {
                if (!valThird) {
                  valThird = cel;
                } else {
                  if (valThird.itemNum < cel.itemNum) {
                    valThird = cel;
                  }
                }
              }
            });
            prnsentList.push(valThird);
          });
        }
      });
      for (var i = prnsentList.length - 1; i >= 0; i--) {
        var targetNode = prnsentList[i];
        for (var j = 0; j < i; j++) {
          if (targetNode.sellgiftId == prnsentList[j].sellgiftId) {
            prnsentList[j].count += targetNode.count;
            prnsentList.splice(i, 1);
            break;
          }
        }
      }
      this.setData({
        prnsentList,
      });
    },
    fetchData() {
      getWxaMsgTpl({
        bizCode: "CANYIN_PLACE_ORDER",
      }).then((res) => {
        if (res.code === 0) {
          let tmplIdsData = res.data;
          this.setData({
            tmplIdsData,
          });
        }
      });
    },
    handleInput(e) {
      let value = e.detail.value;
      this.setData({
        remark: value,
        isShowTextareaPlaceholder: !Boolean(value),
      });
    },
    checkPwdInit() {
      checkPwdInit().then((res) => {
        if (res.code === 0) {
          this.setData({
            isPwdInit: res.data.initialed,
          });
        }
      });
    },
    changeDinnerNum(e) {
      let {
        currentTarget: {
          dataset: { num },
        },
      } = e;
      this.setData({
        temporaryDinnerNum: num,
        tempInputDinnerNum: "",
      });
    },
    handleInputDinnerNum(e) {
      if (e?.detail?.value>999) {
        this.setData({
          tempInputDinnerNum: 999,
          temporaryDinnerNum: 0,
        });
        return
      }
      this.setData({
        tempInputDinnerNum: Number(e?.detail?.value),
        temporaryDinnerNum: 0,
      });
    },
    confirmDinnerNum() {
      let { temporaryDinnerNum, tempInputDinnerNum } = this.data;
      this.setData({
        dinnerNum: temporaryDinnerNum || tempInputDinnerNum,
      });
      let {
        shopInfo: { teaFee, packFee },
        dinnerNum,
        totalFee,
        dinnerType,
      } = this.data;
      if (dinnerNum < 1 || !dinnerNum) {
        return;
      }
      this.setPrice();
      this.setData({
        showChangeDinner: false,
      });
    },
    showDinnerModal() {
      let { shopInfo, dinnerObj } = this.data;
      const { packDinersStatus, hallFoodDinersStatus, deliveryDinersStatus } =
        shopInfo;
      // @ApiModelProperty("打包人数开关 0关 1开")
      //   private Integer packDinersStatus;
      // @ApiModelProperty("堂食人数开关 0关 1开")
      //   private Integer hallFoodDinersStatus;
      // @ApiModelProperty("外卖配送人数开关 0关 1开")
      //   private Integer deliveryDinersStatus;
      switch (dinnerObj.value) {
        case 1:
          this.setData({
            showDinnerNum:
              hallFoodDinersStatus === 1 || hallFoodDinersStatus === "1",
          });
          break;
        case 2:
          this.setData({
            showDinnerNum: packDinersStatus === 1 || packDinersStatus === "1",
          });
          break;
        case 3:
          this.setData({
            showDinnerNum:
              deliveryDinersStatus === 1 || deliveryDinersStatus === "1",
          });
          break;
      }
      if (this.data.showDinnerNum) {
        this.setData({
          showChangeDinner: true,
        });
      }
    },
    // handleChangeOrderType(e) {
    //   let type = Number(e.currentTarget.dataset.type);
    //   let {
    //     shopInfo: {
    //       teaFee,
    //       packFee,
    //     },
    //     dinnerNum,
    //     totalFee,
    //     dinnerType
    //   } = this.data
    //   if (this.data.shopInfo.orderTypes.indexOf(type) === -1) {
    //     wx.showToast({
    //       title: "该门店暂不支持" + orderTypeName[type],
    //       icon: "none",
    //       duration: 3000
    //     });
    //     return
    //   }
    //   this.setData({
    //     orderType: type,
    //     dinnerType: type
    //   })
    //   getApp().globalData.dinnerType = type
    //   if (dinnerNum) {
    //     if (type == 1) {
    //       this.setData({
    //         thildVal: (parseFloat(totalFee * 100 + (teaFee * 100 * dinnerNum)) / 100).toFixed(2)
    //       })
    //     } else {
    //       this.setData({
    //         thildVal: (parseFloat(totalFee * 100 + (packFee * 100)) / 100).toFixed(2)
    //       })
    //     }
    //   }
    // },
    handleSelectCoupon() {
      // 点餐这边的单位都是元...注意单位转换
      if (this.data.dincountList.length <= 0) return;
      router.push({
        name: "selectDiscount",
        params: {
          shopId: this.data.shopInfo.shopId,
          totalFee: $math.mul(this.data.totalFee, 100, 0),
          orderType: 6,
          selectItem: discountMd5(this.data.discountInfo),
        },
        events: {
          change: (discountInfo) => {
            this.changeDiscount(discountInfo);
          },
        },
      });
    },
    handleToRemark() {
      router.push({
        name: "catering/remarks",
        params: {
          remark: this.data.orderRemark,
        },
        events: {
          remarkChange: (remark) => {
            console.info("remarkChange", remark);
            this.setData({
              orderRemark: remark,
            });
          },
        },
      });
    },
    handleAppointTime() {
      let data = {
        shopInfo: this.data.shopInfo,
        isAppointTime: this.data.isAppointTime,
        appointMin: this.data.appointMin,
        appointHour: this.data.appointHour,
      };
      this.selectComponent("#select-time-dialog")
        .open(data)
        .then((res) => {
          console.info("#select-time-dialog", res);
          this.setData({
            isAppointTime: res.isAppointTime,
            appointTime: res.appointTime,
            appointMin: res.appointMin,
            appointHour: res.appointHour,
          });
        });
    },
    autoUseDiscount() {
      let totalFee = this.data.totalFee;

      if (totalFee === 0 || totalFee < 0) {
        return 0;
      }
      let data = {
        orderType: 6,
        shopId: this.data.shopInfo.shopId,
        tradeFee: $math.mul(totalFee, 100, 0),
        // joinMercNo:$cache.get('themeConfig-mall').mercNo
      };
      queryDiscount(data).then((res) => {
        if (res.code === 0) {
          if (this.data.totalFee === totalFee && res.data.length > 0) {
            this.setData({
              dincountList: res.data,
            });
            this.changeDiscount(res.data[0]);
          }
        }
      });
    },
    changeDiscount(discountInfo) {
      // 点餐这边的单位都是元...注意单位转换
      if (discountInfo) {
        this.setData({
          discountInfo: discountInfo,
          discountFee: $math.div(discountInfo.discountFee, 100, 2),
        });
      } else {
        this.setData({
          discountInfo: null,
          discountFee: 0,
        });
      }
    },
    showScanModal() {
      wx.scanCode({
        success: (scanRes) => {
          let url = scanRes.result;
          if (url && url.indexOf("/") !== -1) {
            let index = url.lastIndexOf("/");
            let codeNo = url.substring(index + 1, url.length);
            this.baseQr(codeNo);
          } else {
            wx.showToast({
              title: "无效二维码",
              icon: "none",
              duration: 2000,
            });
          }
        },
      });
    },
    baseQr(codeNo) {
      let data = {
        codeNo: codeNo,
      };
      getQrInfo(data).then((res) => {
        let errMsg = "";
        let data = res.data;
        if (!data || data.bizType !== 1 || !data.bizNo) {
          errMsg = "无效识别码";
        } else if (data.status === 0) {
          errMsg = "识别码未启用";
        } else if (data.bindStatus === 0) {
          errMsg = "识别码未绑定";
        } else if (data.bizShopId !== this.data.shopId) {
          errMsg = "识别码与下单店铺不一致";
        }
        if (errMsg) {
          wx.showModal({
            title: "温馨提示",
            content: errMsg,
            showCancel: false,
            success(res) {},
          });
          return;
        }
        wx.showModal({
          content: `当前桌号${data.bizNo}`,
          cancelText: "重新扫",
          confirmText: "确认下单",
          success: (res) => {
            if (res.confirm) {
              this.setData({
                tableNo: data.bizNo,
              });
              this.handleClickToPay();
            } else if (res.cancel) {
              this.handleClickToPay();
            }
          },
        });
      });
    },
    //支付按钮点击
    async handleClickToPay() {
      let shopStatus = await this.setShopStatus();
      if (!shopStatus) return;
      let self = this;
      let initial = false;
      let {
        accountPayRule: { skipPwdAmount },
      } = this.data;
      const baseInfo = await getBaseInfo();
      let memberCategoryId = baseInfo?.data?.memberCategoryId || "";
      if (memberCategoryId) {
        let {
          data: { initialed },
        } = await checkPwdInit();
        initial = initialed;
      }
      let price = $math.mul(
        $math.sub(this.data.thildVal, this.data.discountFee),
        1,
        0
      );
      if (memberCategoryId && price > skipPwdAmount / 100 && !initial) {
        router.push({
          name: "member/resetPassword",
          params: {
            type: "init",
          },
        });
        return;
      }

      if (this.data.isClick) {
        setTimeout(() => {
          self.setData({
            isClick: false,
          });
        }, 1500);
        return;
      } else {
        self.setData({
          isClick: true,
        });
      }
      if (!this.data.shopInfo.isUseTableNo || this.data.tableNo) {
        if (this.data.tmplIdsData) {
          wxUtils
            .requestSubscribeMessage(this.data.tmplIdsData)
            .then((res) => {
              this.startCreateOrder();
            })
            .catch(() => {
              this.startCreateOrder();
            });
        } else {
          this.startCreateOrder();
        }
      } else {
        this.showScanModal();
      }
    },
    startCreateOrder() {
      let _this = this;
      let {
        dinnerNum,
        dinnerObj: { value: dinnerType },
        deliveryMsg,
      } = this.data;
      let {
        id,
        postalCode,
        date,
        defaulted,
        distance,
        scope,
        tagList,
        ...deliveryInfo
      } = deliveryMsg;

      let data = {
        shopId: this.data.shopId,
        tradeType: 0,
        orderType: dinnerType,
        tableNo: this.data.tableNo,
        phone: this.data.phone,
        isAppointTime: this.data.isAppointTime,
        appointHour: this.data.appointHour,
        appointMin: this.data.appointMin,
        remark: this.data.remark,
        items: this.convertCartList(this.data.cartList),
        discountInfo: this.data.discountInfo,
        storeNo: this.data.shopInfo.storeNo,
        dinersNum: dinnerNum,
        deliveryInfo: dinnerType == 3 ? deliveryInfo : "",
        bookingArriveTime: dinnerType == 3 ? date : "",
      };
      if (dinnerType != 3) {
        delete data.deliveryInfo;
        delete data.bookingArriveTime;
      }
      wx.showLoading({
        title: "下单中...",
        mask: true,
      });
      createOrder(data)
        .then((res) => {
          if (res.code === 0) {
            // 清空购物车
            this.clearCart();
            let payChannels = [];
            if (this.data.shopInfo.payTypes.includes(3)) {
              payChannels.push("balance");
            }
            if (this.data.shopInfo.payTypes.includes(1)) {
              payChannels.push("wx");
            }
            let orderNo = res.data.orderNo;
            let payFee = $math.mul(
              $math.sub(this.data.thildVal, this.data.discountFee),
              100,
              0
            );
            let params = {
              orderNo: res.data.orderNo,
              payFee: payFee > 0 ? payFee : 0,
              hasDiscount: !!this.data.discountInfo,
              payChannels: payChannels,
            };
            wx.hideLoading();
            this.toCateringPay(params)
              .then(() => {
                wx.removeStorageSync(Private_Domain_Meal_Method);
                router.redirectTo({
                  name: "codeorder/orderdetails",
                  params: {
                    orderNo: orderNo,
                    pageFrom: "comfirm",
                  },
                });
              })
              .catch((res) => {
                wx.removeStorageSync(Private_Domain_Meal_Method);
                router.redirectTo({
                  name: "codeorder/orderdetails",
                  params: {
                    orderNo: orderNo,
                    pageFrom: "comfirm",
                  },
                });
              });
          }
        })
        .catch((res) => {
          if (res.data.code == -134) {
            wx.hideToast();
            wx.showModal({
              title: "提示",
              content: "部分商品已售罄,请从新选购",
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  _this.clearCart();
                  router.redirectTo({
                    name: "codeorder/index",
                  });
                }
              },
            });
          }
          wx.hideLoading();
        });
    },
    convertCartList(cartList) {
      let rv = [];
      for (let item of cartList) {
        let specs = [];
        if (item.spec) {
          specs.push(item.spec);
        }
        specs.push(...item.attrList);
        rv.push({
          itemId: item.id,
          count: item.count,
          specName: item.spec,
          specAttrRemark: specs.join(","),
        });
      }
      return rv;
    },
    async setShopStatus() {
      let isOpenTime = true;
      let res = await getShopStatus({
        shopId: this.data.shopId,
      });
      let { isOpen, status, disabled } = res.data;
      isOpenTime =
        isOpen == true && (status == 1 || status == 2) && disabled == false
          ? true
          : false;
      this.setData({
        isOpenTime,
      });
      return isOpenTime;
    },
    handleToChoose() {
      router.push({
        name: "mall/service-stores",
        params: {
          deliveryType: "LOCAL",
          activeTab: "address",
        },
        events: {
          changeAddress: (data) => {
            // 这里切换了配送方式和地址
            this.setAddress(data.address);
          },
        },
      });
    },
    setAddress(data) {
      let { latitude, longitude } = data;
      let { latitude: latitudeShop, longitude: longitudeShop } =
        this.data.shopInfo;
      let distance = getDistance(
        latitudeShop,
        longitudeShop,
        latitude,
        longitude
      );
      data.distance = (distance / 1000).toFixed(2);
      this.setData({
        deliveryMsg: data,
      });
      this.setErrMsg();
    },
    setErrMsg() {
      let {
        totalFee,
        deliveryMsg,
        shopInfo,
        dinnerObj: { value },
      } = this.data;
      let errMsg = "";
      console.log(deliveryMsg);
      if (value == 3) {
        if (totalFee < shopInfo.startingPriceDelivery) {
          errMsg = `不足起送价${shopInfo.startingPriceDelivery}元`;
          this.setData({
            errMsg,
          });
          return;
        }
        if (!deliveryMsg.userName) {
          errMsg = "请先选择配送地址";
          this.setData({
            errMsg,
          });
          return;
        }
        if (deliveryMsg?.distance > shopInfo.distanceDelivery) {
          errMsg = "地址超出了店铺的配送范围，请确认收货地址";
          this.setData({
            errMsg,
          });
          return;
        }

        if (!deliveryMsg?.date) {
          errMsg = "请选择预约送达时间";
          this.setData({
            errMsg,
          });
          return;
        }
      }
      this.setData({
        errMsg,
      });
    },
    handleUpdateArrivalTime(data) {
      let { detail } = data;
      this.setData({
        "deliveryMsg.date": detail,
      });
      this.setErrMsg();
    },
    selectTime() {
      this.selectComponent("#selectTime").open();
    },
    setTimeDialogOptions() {
      if (!this?.data?.shopInfo) return;
      let {
        shopInfo: { stockUp, openTimeStr, closeTimeStr },
      } = this.data;
      let nowDay = dayjs().format("HH:mm");
      let nowTime =
        Number(nowDay.split(":")[0]) * 60 +
        Number(nowDay.split(":")[1]) +
        stockUp * 60;
      let week = dayjs().day();
      let endTime =
        Number(closeTimeStr.split(":")[0]) * 60 +
        Number(closeTimeStr.split(":")[1]);
      let beginTime =
        Number(openTimeStr.split(":")[0]) * 60 +
        Number(openTimeStr.split(":")[1]);
      let weekDays = nowTime > endTime ? `${week},${week + 1}` : `${week}`;
      let serviceTimes = [
        {
          beginTime,
          endTime,
          weekDays,
        },
      ]; //营业时间
      this.setData({
        "deliveryOptions.prepareTime": stockUp * 60, //设置备货时间
        "deliveryOptions.serviceTimes": serviceTimes, // 设置营业时间
      });
      // this.selectComponent("#selectTime").init()
    },
    setPrice() {
      let {
        dinnerObj: { value: dinnerType, extraFree, extraFree2 },
        totalFee,
        dinnerNum,
      } = this.data;
      let thildVal = 0;
      switch (dinnerType) {
        case 1:
          thildVal = (
            parseFloat(totalFee * 100 + extraFree * 100 * dinnerNum) / 100
          ).toFixed(2);
          break;
        case 2:
          thildVal = (
            parseFloat(totalFee * 100 + extraFree * 100) / 100
          ).toFixed(2);
          break;
        case 3:
          thildVal = (
            parseFloat(totalFee * 100 + extraFree * 100 + extraFree2 * 100) /
            100
          ).toFixed(2);
          break;
      }
      this.setData({
        thildVal,
      });
    },
    openDinner() {
      let {
        shopInfo: { orderTypes },
      } = this.data;
      if (orderTypes.length < 2) return;
      this.selectComponent("#choose-dinner").open();
    },
    setDinner(data) {
      let {
        detail: { item },
      } = data;
      let { shopInfo } = this.data;
      if (item.value === 3) {
        nearByAddress(shopInfo).then((res) => {
          if (res.code === 0) {
            this.setAddress(res.data);
          }
        });
      }
      wx.setStorageSync(Private_Domain_Meal_Method, JSON.stringify(item));
      this.setData({
        dinnerObj: item,
        dinnerNum: "",
        temporaryDinnerNum: 1,
      });
      this.setPrice();
      this.showDinnerModal();
      this.setErrMsg();
    },
  },
});
